<template>
<view>
<!--hotmall/packageB/address/address.wxml-->
<!-- <text>hotmall/packageB/address/address.wxml</text> -->
<view class="container">
  <view v-for="(item, index) in items" :key="index" :class="'touch-item ' + (item.isTouchMove ? 'touch-move-active' : '')" :data-index="index" @touchstart="touchstart" @touchmove="touchmove" v-if="status == 1">
    <view class="content" @tap="changeAddress" :data-index="index">
      <view class="left">
        <view>{{item.name}}</view>
        <view class="moren" v-if="item.is_default == 1">默认</view>
      </view>
      <view class="conter">
        <view class="conter_phone">{{item.phone}}</view>
        <view class="conter_site">{{item.addr}}{{item.address}}</view>
      </view>
      <view class="right">
      </view>
    </view>
    <view class="del" @tap.stop="del" :data-index="index">删除</view>
  </view>
</view>
<view class="nodata" v-if="status == 0 && page == 1">
  <image src="/static/remao_shop/img/dress_icon.png"></image>
  <view>
    <text class="nodatatext">收货地址在哪里？</text>
  </view>
</view>
<view class="nopage" v-if="status == 0 && page > 1">没有了</view>
<form report-submit="true" @submit="submit">
  <view class="bottom">

    <button class="add" @tap="add" formType="submit">
      +新建地址
    </button>
    <button class="onekey" @tap="onekey" formType="submit">
      一键导入微信地址
    </button>
  </view>
</form>
</view>
</template>

<script>
import api from "../../../api";
var app = getApp();

export default {
  data() {
    return {
      items: [],
      startX: 0,
      //开始坐标
      startY: 0,
      address: [],
      adid: '',
      uid: 0,
      status: 1,
      page: 1
    };
  },

  components: {},
  props: {},
  onLoad: function () {
    wx.getStorage({
      key: 'userId',
      success: res => {
        this.setData({
          uid: res.data
        });
        this.getList();
      }
    });
    this.setData({
      items: this.items
    });
  },

  onShow() {
    this.onLoad();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.status != 0) {
      this.setData({
        page: this.page + 1
      });
      this.getList();
    }
  },

  onPullDownRefresh() {
    wx.stopPullDownRefresh();
  },

  methods: {
    changeAddress: function (e) {
      console.log(e.currentTarget.dataset.index);
      let that = this;
      let index = e.currentTarget.dataset.index;
      wx.request({
        url: api.default.editaddress,
        method: 'POST',
        data: {
          address_id: that.items[index].address_id,
          uid: that.uid,
          name: that.items[index].name,
          phone: that.items[index].phone,
          province: that.items[index].province,
          city: that.items[index].city,
          area: that.items[index].district,
          addr: that.items[index].address,
          is_default: 1
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: res => {
          console.log(res);
          wx.showToast({
            title: res.data.msg,
            duration: 1000
          });
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            });
          }, 1000);
        }
      });
    },
    //手指触摸动作开始 记录起点X坐标
    touchstart: function (e) {
      //开始触摸时 重置所有删除
      this.items.forEach(function (v, i) {
        if (v.isTouchMove) //只操作为true的
          v.isTouchMove = false;
      });
      this.setData({
        startX: e.changedTouches[0].clientX,
        startY: e.changedTouches[0].clientY,
        items: this.items
      });
    },
    //滑动事件处理
    touchmove: function (e) {
      var that = this,
          index = e.currentTarget.dataset.index,
          //当前索引
      startX = that.startX,
          //开始X坐标
      startY = that.startY,
          //开始Y坐标
      touchMoveX = e.changedTouches[0].clientX,
          //滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY,
          //滑动变化坐标
      //获取滑动角度
      angle = that.angle({
        X: startX,
        Y: startY
      }, {
        X: touchMoveX,
        Y: touchMoveY
      });
      that.items.forEach(function (v, i) {
        v.isTouchMove = false; //滑动超过30度角 return

        if (Math.abs(angle) > 30) return;

        if (i == index) {
          if (touchMoveX > startX) //右滑
            v.isTouchMove = false;else //左滑
            v.isTouchMove = true;
        }
      }); //更新数据

      that.setData({
        items: that.items
      });
    },

    /**
     *计算滑动角度
     * @param {Object} start 起点坐标
     * @param {Object} end 终点坐标
     */
    angle: function (start, end) {
      var _X = end.X - start.X,
          _Y = end.Y - start.Y; //返回角度 /Math.atan()返回数字的反正切值


      return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
    },
    //删除事件
    del: function (e) {
      console.log(e.target.dataset.index);
      var l = e.target.dataset.index;
      console.log(this.adid[l]);
      wx.showModal({
        content: '确认删除吗',
        success: res => {
          console.log(res);

          if (res.confirm == true) {
            app.globalData.request({
              url: api.default.deladdress,
              method: 'POST',
              data: {
                uid: this.uid,
                address_id: this.adid[l]
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: res => {
                console.log(res);
                wx.showToast({
                  title: res.msg
                });
                this.getList();
              }
            });
          }
        }
      });
    },

    //添加地址
    add() {
      wx.redirectTo({
        url: '../../packageB/addaddress/addaddress?abc=' + 1
      });
    },

    //获取微信地址跳转
    onekey() {
      wx.chooseAddress({
        success(res) {
          console.log(res.userName);
          console.log(res.postalCode);
          console.log(res.provinceName);
          console.log(res.cityName);
          console.log(res.countyName);
          console.log(res.detailInfo);
          console.log(res.nationalCode);
          console.log(res.telNumber);
          console.log(res);
          var data = JSON.stringify(res);
          wx.redirectTo({
            url: '../../packageB/addaddress/addaddress?res=' + data + "&abc=" + 1
          });
        }

      });
    },

    //修改地址
    edit: function (e) {
      console.log(e);
      var l = e.currentTarget.dataset.index;
      console.log(this.adid[l]);
      wx.navigateTo({
        url: '../../packageB/editaddress/editaddress?res=' + this.adid[l]
      });
    },

    //获取收货地址列表
    getList() {
      console.log(this.uid);
      app.globalData.request({
        url: api.default.address,
        method: 'POST',
        data: {
          uid: this.uid,
          page: this.page
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: res => {
          console.log(res);

          if (this.page == 1) {
            if (res.status == 0) {
              this.setData({
                status: res.status
              });
              console.log(this.status);
            } else {
              let name = [];

              for (let i = 0; i < res.list.length; i++) {
                name = name.concat(res.list[i].address_id); // console.log(name)
              }

              this.setData({
                items: res.list,
                adid: name
              });
              console.log(this.adid);
              console.log(this.items);
            }
          } else {
            if (res.status == 0) {
              this.setData({
                status: res.status
              });
              console.log(this.status);
            } else {
              let name = [];
              var adid = this.adid;
              var items = this.items;

              for (let i = 0; i < res.list.length; i++) {
                name = name.concat(res.list[i].address_id); // console.log(name)

                adid.push(name[i]);
                items.push(res.list[i]);
              }

              this.setData({
                items: items,
                adid: adid
              });
              console.log(this.adid);
              console.log(this.items);
            }
          }
        }
      });
    },

    submit(e) {
      console.log(e);
      var a = e.detail.formId;
      wx.getStorage({
        key: 'userId',
        success: function (aaa) {
          console.log(aaa.data);
          var open = aaa.data;
          console.log(open);

          if (a == 'the formId is a mock one') {
            wx.showToast({
              title: '请用手机测试'
            });
          } else {
            console.log(a);
            app.globalData.request({
              url: api.gzSea.test,
              //仅为示例，并非真实的接口地址
              data: {
                form_id: a,
                user_id: open
              },
              method: 'POST',
              header: {
                'content-type': 'application/x-www-form-urlencoded' // 默认值

              },

              success(res) {
                console.log(res);
              }

            });
          }
        }
      });
    }

  }
};
</script>
<style>
@import "./changeAddress.css";
</style>